﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using dotGen.CustomTool.Fx;
using Microsoft.Win32;

namespace dotGen
{
    [ComVisible(true)]
    [Guid(dotGenerator.Guid)]
    public sealed class dotGenerator : BaseCodeGeneratorWithSite
    {
        internal const string Guid = "2496303D-3F4A-4fad-AD2A-A0EEF3AFC6D1";

        public override string GetDefaultExtension()
        {
            return ".designer" + base.GetDefaultExtension();
        }

        protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
        {
            try
            {
                var engine = new dotGenEngine();
                string result =
                    engine.Generate(inputFileContent.Split(new string[] {Environment.NewLine}, StringSplitOptions.None));
                return Encoding.UTF8.GetBytes(result);
            }
            catch (Exception ex)
            {
                return Encoding.UTF8.GetBytes(ex.ToString());
            }
        }

        #region Registration tasks

        private const string KeyPathFormat = @"SOFTWARE\Microsoft\VisualStudio\{0}\Generators\{1}\{2}";
        private const string CSGeneratorCategory = "{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}";
        private const string CustomToolName = "dotGenerator";
        private const string CustomToolDescription = "dotGen Custom Tool for Visual Studio 2008";

        [ComRegisterFunction]
        public static void RegisterCom(Type type)
        {
            AddToRegistry("9.0", CSGeneratorCategory);
        }

        [ComUnregisterFunction]
        public static void UnregisterCom(Type type)
        {
            RemoveFromRegistry("9.0", CSGeneratorCategory);
        }

        private static void AddToRegistry(string version, string category)
        {
            string path = String.Format(KeyPathFormat, version, category, CustomToolName);
            using (RegistryKey key = Registry.LocalMachine.CreateSubKey(path))
            {
                key.SetValue(string.Empty, CustomToolDescription);
                key.SetValue("CLSID", "{" + Guid + "}");
                key.SetValue("GeneratesDesignTimeSource", 1);
            }
        }

        private static void RemoveFromRegistry(string version, string category)
        {
            string path = string.Format(KeyPathFormat, version, category, CustomToolName);
            Registry.LocalMachine.DeleteSubKey(path, false);
        }

        #endregion
    }
}
